package org.grayrabbit.cms.publish.generate;

import java.util.List;

import org.grayrabbit.cms.entity.Admin;
import org.grayrabbit.cms.entity.PublishLog;
import org.grayrabbit.cms.entity.PublishTask;
import org.grayrabbit.cms.entity.Site;
import org.grayrabbit.cms.publish.api.Generatable;
import org.grayrabbit.cms.publish.generate.factory.AbstractFactory;
import org.grayrabbit.cms.publish.generate.factory.MissionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DeamonThread implements Runnable {
	
	private static Logger log = LoggerFactory.getLogger(DeamonThread.class);
	
	private String genType;
	private String modelType;
	private List<String> targetIds;
	private Site site;
	private Admin admin;
	private String ip;
	private boolean end = false;
	private PublishTask publishTask;
	private Generatable generatable;
	private int pageSize;
	private int pageNum;
	
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}
	public  DeamonThread(String genType,String modelType,List<String> targetIds,Site site,Admin admin,String ip,PublishTask publishTask,Generatable generatable){
		this.genType = genType;
		this.modelType = modelType;
		this.targetIds = targetIds;
		this.site =site;
		this.admin = admin;
		this.ip = ip;
		this.publishTask = publishTask;
		this.generatable = generatable;
	}
	public void run() {
		final Mission mission = getMission();
		mission.setGeneratable(generatable);
		boolean init = false;
		while(!end && mission !=null){
			boolean wait;
			synchronized (AbstractFactory.LOCK) {//读数据加锁
				if(AbstractFactory.PUBLISHSTATUS.get(mission.getPercentKey())!=null && !AbstractFactory.PUBLISHSTATUS.get(mission.getPercentKey()).booleanValue()){
					log.debug("当前任务{},已停止！",mission.getPercentKey());
					publishTask.setTaskStatus(PublishTask.STATUS_STOP);//任务被暂停
					generatable.savePublishTask(publishTask);
					PublishLog publishLog = new PublishLog();
					publishLog.setIsError(Boolean.TRUE);
					publishLog.setPublishInfo("当前任务被停止");
					generatable.savePublishLog(publishLog);
					end = true;
					AbstractFactory.PUBLISHSTATUS.remove(publishTask.getTaskName());//任务停止，删除执行的任务状态
					AbstractFactory.PUBLISHMAP.remove(publishTask.getTaskName());//任务停止，删除任务执行的对应的任务ID
					AbstractFactory.percent.remove(publishTask.getTaskName()+AbstractFactory.FINISHED);//任务停止，删除任务执行对应的任务完成总数
					AbstractFactory.percent.remove(publishTask.getTaskName()+AbstractFactory.FAIL);//任务结束，删除任务执行对应的任务失败总数
					AbstractFactory.percent.remove(publishTask.getTaskName()+AbstractFactory.TOTAL);//任务停止，删除任务执行对应的任务总数
					continue;
				}
				if(AbstractFactory.taskNum>=2){
					wait = true;
				}else{
					if(mission.hasNext()){
						log.info("当前线程启动数:{}",AbstractFactory.taskNum);
						GenTask genTask =mission.next();
						if(genTask==null)
							throw new IllegalArgumentException("生成任务为空!");
						genTask.setGeneratable(generatable);
						genTask.setIp(ip);
						genTask.setPercentKey(mission.getPercentKey());
						genTask.setPublishTask(publishTask);
						genTask.setPageSize(pageSize);
						genTask.setPageNum(pageNum);
						AbstractFactory.taskNum++;
						log.debug("after ++ ,current Task num is {}.",AbstractFactory.taskNum);
						//初始化当前任务的总数与完成数
						if(!init){
							AbstractFactory.percent .put(mission.getPercentKey()+AbstractFactory.TOTAL,Integer.valueOf(mission.getTotal()));
							publishTask.setTaskStatus(PublishTask.STATUS_RUNNING);//任务执行状态
							publishTask.setTotal(Integer.valueOf(mission.getTotal()));
							generatable.savePublishTask(publishTask);//更新总任务数
							AbstractFactory.percent .put(mission.getPercentKey()+AbstractFactory.FINISHED,Integer.valueOf(0));
							AbstractFactory.percent .put(mission.getPercentKey()+AbstractFactory.FAIL,Integer.valueOf(0));
							init = true;
						}
						Thread thread= new Thread(genTask);
						thread.setName(genTask.getType());//定义线程名称，便于跟踪分析
						thread.start();
						log.info("任务进入队列，进行生成，当前任务数：{}",AbstractFactory.taskNum);
					}else{
						end = true;
					}
					wait = false;
				}
			}
			if (wait) {
				try {
					Thread.sleep(1000);//休息一秒钟再重试
				} catch (InterruptedException e) {
				}
				continue;
			}
		}
	}
	private Mission getMission(){
		MissionFactory factory = new MissionFactory(generatable);
		return factory.create(genType, modelType,ip, targetIds, site, admin);
	}
	
}
